#
# "@(#) $Id: RadioView.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
from RadioViewItem import *
from TrackView import *
from Utils.PListParser import *
from DB.Track import *
from Utils.Paths import *
from RadioTrackDialog import *
from DB.RadioLibrary import *

class RadioView(TrackView,KListView):
	def __init__(self,container):
		TrackView.__init__(self)
		KListView.__init__(self,container,"audiocd")
		self.setAllColumnsShowFocus(True)
		self.setRootIsDecorated(True)
		self.loadHeaders()
		c = QColor(237,243,254)
		self.setAlternateBackground(c)
		self.library = RadioLibrary.singleton()
		self.totalCount = 0
		self.loadTrackItems()
		QObject.connect(self.library,PYSIGNAL("injectedItem"),self.loadTrackItems)
		QObject.connect(self.library,PYSIGNAL("removedItem"),self.loadTrackItems)
		QObject.connect(self.library,PYSIGNAL("fetched"),self.loadTrackItems)
		QObject.connect(self,SIGNAL("contextMenuRequested(QListViewItem *, const QPoint &, int)"),self.contextMenu)
		QObject.connect(self,SIGNAL("expanded(QListViewItem*)"),self.itemExpanded)
		QObject.connect(self,SIGNAL("collapsed(QListViewItem*)"),self.itemCollapsed)

	def loadHeaders(self):
		headers = [i18n("Stream"),i18n("Bit Rate"),i18n("Description")] 
		widths = [300,75,300]
		for index in xrange(0,len(headers)):
			self.addColumn(headers[index],widths[index])
		self.setColumnAlignment(1,Qt.AlignRight)
		self.setShowSortIndicator(True)
		self.setFullWidth(True)
		#self.setItemMargin(3)
		sortColumn = self.settings.get('Radio Library Sort Column',0)
		sortAscending = self.settings.get('Radio Library Sort Ascending',True)
		self.setSorting(sortColumn,sortAscending)
		QObject.connect(self.header(),SIGNAL("indexChange(int,int,int)"),self.columnIndexChanged)
		QObject.connect(self.header(),SIGNAL("sizeChange(int,int,int)"),self.columnSizeChanged)
		self.loadHeaderSizes('Radio Library Header Widths')
		self.loadHeaderOrdering('Radio Library Header Map')

	def loadTrackItem(self,track,parent):
		#print "adding",track,"as child of",parent
		item = RadioViewItem(parent,track)

	def loadTrackItems(self):
		self.clear()
		genres = self.library.genres()
		self.totalCount = 0
		for genre in genres:
			genreViewItem = RadioGenreViewItem(self,genre)
			tracks = self.library.tracksForGenre(genre)
			count = 0
			for track in tracks:
				self.loadTrackItem(track,genreViewItem)
				count = count+1
				self.totalCount = self.totalCount+1
			genreViewItem.setText(0,unikode(i18n("%s    (%d stations)")) % (genreViewItem.text(0),count))
		self.restoreItemsState()
		self.emit(PYSIGNAL("changed"),(self,None))
		
	def contentsMouseDoubleClickEvent(self,event):
		pos = self.contentsToViewport(event.pos())
		item = self.itemAt(pos)
		if item:
			item.contentsMouseDoubleClickEvent(event)

	def selectedTrackIDs(self):
		result = []
		item = self.firstChild()
		while item:
			if item.isSelected():
				try:
					result.append(item.trackID())
				except: pass
			item = item.itemBelow()
		return result

	def selectedTracks(self):
		result = []
		item = self.firstChild()
		while item:
			if item.isSelected():
				result.append(item.track())
			item = item.itemBelow()
		return result
	
	def canExport(self):
		return False
	
	def canBurn(self):
		return False

	def canGetInfo(self):
		return False

	def canStream(self):
		return True

	def addStream(self):
		self.library.addStream()
##~ 		addStreamDialog = RadioTrackDialog()
##~ 		ret = addStreamDialog.exec_loop()
##~ 		if ret==QDialog.Accepted:
##~ 			plist = addStreamDialog.unload()
##~ 			self.library.injectPList(plist)

	def contextMenu(self,item,pos,col):
		if item:
			item.contextMenu(pos,col)

	def setSorting(self,column,ascending):
		KListView.setSorting(self,column,ascending)
		self.settings['Radio Library Sort Column'] = column
		self.settings['Radio Library Sort Ascending'] = not not ascending

	def columnIndexChanged(self,section,fromIndex,toIndex):
		self.saveHeaderOrdering('Radio Library Header Map')
	
	def columnSizeChanged(self,section,oldSize,newSize):
		self.saveHeaderSizes('Radio Library Header Widths')
	
	def itemExpanded(self,item):
		self.saveItemsState()
	
	def itemCollapsed(self,item):
		self.saveItemsState()
	
	def saveItemsState(self):
		result = []
		item = self.firstChild()
		while item:
			if item.isOpen(): result.append(item.genre)
			item = item.nextSibling()
		self.settings['Radio Genres Open'] = result
	
	def restoreItemsState(self):
		genres = self.settings.get('Radio Genres Open',None)
		if genres:
			for genre in genres:
				item = self.firstChild()
				while item:
					if item.genre==genre:
						item.setOpen(True)
						break
					item = item.nextSibling()
				
	def canDelete(self):
		return False

	def getSummary(self):
		return unikode(i18n("%d stations")) % self.totalCount
